////////////////////////////////////////////////////////////////////////////////
//
//  FLYING KIWI BV
//  Copyright 2010 Flying Kiwi BV
//  All Rights Reserved.
//
//  NOTICE: Flying Kiwi permits you to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package plantool.modules.users.display {
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	
	import caurina.transitions.Tweener;
	import caurina.transitions.properties.ColorShortcuts;
	
	import kiwi.components.Button;
	import kiwi.components.DragObject;
	import kiwi.components.IDropTarget;
	import kiwi.display.DisplayObject;
	import kiwi.display.Image;
	import kiwi.events.CallbackEvent;
	import kiwi.utils.Validation;
	
	import plantool.data.QueryErrorResult;
	import plantool.data.QueryResult;
	import plantool.display.skins.EmptySkin;
	import plantool.helpers.TextFieldHelper;
	import plantool.modules.calendar.display.CalendarDay;
	import plantool.modules.users.Users;
	import plantool.modules.users.data.UserHourTypes;
	import plantool.modules.workplaces.display.IWorkplaceDay;
	import plantool.modules.workplaces.display.IWorkplaceRow;

	//--------------------------------------------------------------------------
	//  Imports
	//--------------------------------------------------------------------------
	//--------------------------------------------------------------------------
	//  [Metadata (Events, Style, Effects etc)]
	//--------------------------------------------------------------------------
	
	//--------------------------------------------------------------------------
	//  Class declaration
	//--------------------------------------------------------------------------
	public class UserRow extends UserDisplayObject implements IUserRow {
		//--------------------------------------------------------------------------
		//Class constants
		//--------------------------------------------------------------------------
		
		//--------------------------------------------------------------------------
		//Class variables
		//--------------------------------------------------------------------------
		private var _tf:TextField			= null;
		private var _hotspot:DragObject		= null;
		private var _sortHotspot:Button		= null;
		private var _userIcon:Image			= null;
		private var _height:Number			= 20;
		
		//--------------------------------------------------------------------------
		//Class properties
		//--------------------------------------------------------------------------
		override public function get height():Number 			{ return _height; }
		override public function set height(value:Number):void 	{ _height = value; invalidate(); }
		
		public override function get width():Number {
			if (Validation.isSet(_sortHotspot)) {
				return super.width - _sortHotspot.width;
			}
			
			return super.width;
		}
		
		//--------------------------------------------------------------------------
		//Constructor and Destructor
		//--------------------------------------------------------------------------
		public function UserRow() {
			super();
			
			ColorShortcuts.init();
			
			//draw black background
			graphics.clear();
			graphics.beginFill(0);
			graphics.drawRect(0, 0, 145, _height);
			graphics.endFill();
			
			//create textfield
			_tf			= TextFieldHelper.createInfoTf();
			_tf.width	= 135;
			_tf.x		= 5;
			_tf.y		= (_height - _tf.height) / 2;
			addChild(_tf);
			
			//create hotspot
			_hotspot						= new DragObject();
			_hotspot.skin					= new EmptySkin();
			_hotspot.width 					= 135;
			_hotspot.height					= _height;
			_hotspot.validateDropHandler 	= onValidateDrop;
			_hotspot.droppedHandler			= onDrop;
			
			//edit user on dblclick
			_hotspot.doubleClickEnabled = true;
			_hotspot.addEventListener(MouseEvent.DOUBLE_CLICK		, onDblClick_user);
			
			//create droptargets
			_hotspot.dropTargets.push(IWorkplaceDay);
			_hotspot.dropTargets.push(CalendarDay);
			_hotspot.dropTargets.push(IWorkplaceRow);
			
			//add hotspot
			addChild(_hotspot);
			
			//create sorting hotspot
			_sortHotspot				= new Button();
			_sortHotspot.width			= 10;
			_sortHotspot.height			= _height;
			_sortHotspot.skin			= new UserSortingSkin();
			_sortHotspot.x				= -_sortHotspot.width;
			_sortHotspot.mouseHandler 	= sortingHotspotMouseHandler;
			addChild(_sortHotspot);
		}
		
		public override function dispose():void {
			removeEventListener(Event.ENTER_FRAME					, onSorting_enterFrame);
			base.stage.removeEventListener(MouseEvent.MOUSE_UP		, onSorting_mouseUp);
			
			if (Validation.isSet(_hotspot)) {
				_hotspot.removeEventListener(MouseEvent.DOUBLE_CLICK		, onDblClick_user);
				_hotspot.dispose();
				_hotspot = null;
			}
			
			if (Validation.isSet(_sortHotspot)) {
				_sortHotspot.dispose();
				_sortHotspot = null;
			}
			
			if (Validation.isSet(_userIcon)) {
				_userIcon.dispose();
				_userIcon = null;
			}
			
			if (Validation.isSet(_tf)) {
				if (contains(_tf)) {
					removeChild(_tf);
				}
				_tf = null;
			}
			
			super.dispose();
		}
		
		//--------------------------------------------------------------------------
		//Class methods
		//--------------------------------------------------------------------------
		private function sortingHotspotMouseHandler(e:CallbackEvent):void {
			switch ((e.userData as MouseEvent).type) {
				case MouseEvent.MOUSE_DOWN:
					//add enterframe and mouseUp event
					addEventListener(Event.ENTER_FRAME					, onSorting_enterFrame);
					base.stage.addEventListener(MouseEvent.MOUSE_UP		, onSorting_mouseUp);
					
					//set top-most
					parent.setChildIndex(this, parent.numChildren -1);
					break;
				/*case MouseEvent.MOUSE_OVER:
					_sortHotspot.graphics.clear();
					_sortHotspot.graphics.beginFill(0xFF0000);
					_sortHotspot.graphics.drawRect(0, 0, _sortHotspot.width, _sortHotspot.height);
					_sortHotspot.graphics.endFill();
					break;
				case MouseEvent.MOUSE_OUT:
					_sortHotspot.graphics.clear();
					break;
				*/
			}
		}
		
		private function onComplete_saveSorting():void {
			trace("sorting complete");
		}
		
		private function onComplete_getUserIcon(e:CallbackEvent):void {
			//get userIcon
			_userIcon 		= e.currentTarget as Image;
			
			//set icon width and height
			var scale:Number = _height / _userIcon.height;
			_userIcon.scaleX = _userIcon.scaleY = scale;
			
			//color icon
			Tweener.addTween(_userIcon, { _color:user.color });
			
			//set icon for dragging
			_hotspot.dragItem 	= _userIcon;
		}
		
		private function onComplete_saveUserDay(result:QueryResult):void {
		}
		
		private function onDblClick_user(e:MouseEvent):void {
			userApi.showForm(user);
		}
		
		private function onDrop(target:IDropTarget, item:DragObject):void {
			//validate target
			if (target is IWorkplaceDay) {
				userApi.createWholeDayForUser((target as IWorkplaceDay).date, (target as IWorkplaceDay).workplace.id, user, UserHourTypes.USER_WORKPLACE);
			}
			if (target is IWorkplaceRow) {
				userApi.createWholeWeekForUser((target as IWorkplaceRow).workplace.id, user, UserHourTypes.USER_WORKPLACE);
			}
			if (target is CalendarDay) {
				userApi.createWholeDayForUser((target as CalendarDay).date, 0, user, UserHourTypes.USER_FREE);
			}
		}
		
		private function onError_query(result:QueryErrorResult):void {
			trace("Error", result.message, result.query);
		}
		
		private function onSorting_enterFrame(e:Event):void {
			//update sorting for this row
			var pos:Point 	= parent.globalToLocal(new Point(base.stage.mouseX, base.stage.mouseY));
			this.x			= pos.x + (_sortHotspot.width / 2);
			this.y			= pos.y - (_sortHotspot.height / 2);
			Users.getInstance().updateRowSorting(this);
		}
		
		private function onSorting_mouseUp(e:MouseEvent):void {
			//remove enterframe and mouseUp event
			removeEventListener(Event.ENTER_FRAME					, onSorting_enterFrame);
			base.stage.removeEventListener(MouseEvent.MOUSE_UP		, onSorting_mouseUp);
			
			//update sorting for this row
			Users.getInstance().positionRow(this, -1, null);
			Users.getInstance().updateRowSorting(this);
			Users.getInstance().saveUsers();
		}
		
		private function onValidateDrop(target:IDropTarget, item:DragObject):Boolean {
			//TODO: Validate drop
			return true;
		}
		
		protected override function init():void {
			//load icon to show for dragging
			_userIcon	= new Image(base.config.BASEURL + "data/images/user-icon.png", onComplete_getUserIcon);
			
			//call super init
			super.init();
		}
		
		public function addDay(day:IUserDay):void {
			//position day
			var daypos:int				= 0;
			var list:Vector.<Date>		= dateApi.getVisibleDates();
			for (var i:uint = 0; i < list.length; i++) {
				if (list[i].valueOf() == day.date.valueOf()) {
					daypos = i;
					break;
				}
			}
			(day as DisplayObject).x 	= 145 + (daypos * (day as DisplayObject).width);
			
			//add day
			addChild((day as DisplayObject));
		}
		
		public override function draw():void {
			//set username
			if (Validation.isSet(_tf)) {
				_tf.text = user.username;
			}
			
			//color icon
			if (Validation.isSet(_userIcon)) {
				Tweener.addTween(_userIcon, { _color:user.color });
			}
		}
	}
}